package services.snapchat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.HashMap;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import services.Utils;

class SnapchatAgent {

	private static final String VERSION = "6.1.2"; // TODO warning!
	private static final String URL = "https://feelinsonice-hrd.appspot.com/bq";
	private static final String SECRET = "iEk21fuwZApXlz93750dmW22pw389dPwOk";
	private static final String HASH_PATTERN = "0001110111101110001111010101111011010001001110011000110001000110";
	
	private static final String STATIC_TOKEN = "m198sOkJEn37DjqZ32lpRu76xmw288xSQ9";
	
	public SnapchatAgent() {
		// TODO Auto-generated constructor stub
	}
	
	public JSONObject post(String endpoint, HashMap<String, String> data, int timestamp, String auth_token) {
		
		String token = (auth_token != null) ? auth_token : STATIC_TOKEN;
		data.put("req_token", hash(token, String.valueOf(timestamp)));
		data.put("version", VERSION);
		
		String query = Utils.toQueryString(data);
		URL url;
		HttpURLConnection conn = null;
		try {
			url = new URL(URL + endpoint);
			conn = Utils.getPostConnection(url, query);
			conn.connect();
			
			String response = "";	        
	        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String inputLine;
			while ((inputLine = reader.readLine()) != null) response += inputLine;
			reader.close();

			System.out.println("Request ended, response message: " + response);
			
			JSONParser parser = new JSONParser();
			JSONObject jsonData = (JSONObject) parser.parse(response);
			
			return jsonData;
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (conn != null) conn.disconnect();
		}

	}

	private String hash(String first, String second) {
		System.out.println("SnapchatAgent.hash("+ first +", "+ second +")...");
		String result;
		
		try {
			
			MessageDigest md1;
			md1 = MessageDigest.getInstance("SHA-256");
			md1.update((SECRET + first).getBytes("UTF-8"));
			String hash1 = Utils.getHashString(md1.digest());
			System.out.println("Generated hash1 (length = "+ hash1.length() +") = " + hash1);
			
			
			MessageDigest md2 = MessageDigest.getInstance("SHA-256");
			md2.update((second + SECRET).getBytes("UTF-8"));
			String hash2 = Utils.getHashString(md2.digest());
			System.out.println("Generated hash2 (length = "+ hash2.length() +") = " + hash2);
			
			// combine using the pattern
			result = "";
			for (int i = 0; i < HASH_PATTERN.length(); i++) {
				result += ((HASH_PATTERN.charAt(i) == '1') ? hash2.charAt(i) : hash1.charAt(i));
			}

			System.out.println("Final hash = " + result);
			return result;
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}